package com.wimcorp.magic.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import com.wimcorp.magic.board.PlayingDeck;

@Transactional
public class PlayingDeckDaoImpl implements PlayingDeckDao {

	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public long saveOrUpdate(PlayingDeck o) {
		if (o.getId() == null) {
			entityManager.persist(o);
			return o.getId();
		} else {
			return entityManager.merge(o).getId();
		}
	}

	@Override
	@Transactional
	public PlayingDeck getDeck(long id) {
		List<PlayingDeck> decks = entityManager
				.createQuery("select d from PlayingDeck d where id=:id", PlayingDeck.class).setParameter("id", id)
				.getResultList();
		if (decks.size() > 0) {
			//PlayingDeck playingDeck = decks.get(0);
			//Hibernate.initialize(playingDeck);
			return decks.get(0).clone();
		} else {
			return null;
		}
	}

	@Override
	public List<PlayingDeck> getAll() {
		List<PlayingDeck> decks = entityManager
				.createQuery("select d from PlayingDeck d", PlayingDeck.class)
				.getResultList();
		return decks;
	}

	

}
